<script setup>
import {
  userRegisterService,
  userLoginService,
  userCodeService,
  userLoginAdminService
} from '@/api/user.js'
import { User, Lock, Message, EditPen } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const isRegister = ref(false)
const form = ref()

// 登录和注册数据对象
const formModel = ref({
  userId: '',
  nickname: '',
  email: '',
  code: '',
  password: '',
  repassword: ''
})
const rules = {
  userId: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  nickname: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 4,
      max: 8,
      message: '用户名必须为4-8个有效字符',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入正确的邮箱账号',
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 邮箱验证码
const countdown = ref(59)
const isDisabled = ref(false)

const startCountdown = async () => {
  isDisabled.value = true
  let timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
      isDisabled.value = false
      countdown.value = 59
    }
  }, 1000)
  await form.value.validate()
  await userCodeService(formModel.value.email)
}

const register = async () => {
  // 注册成功之前，先进行校验，校验成功 → 请求，校验失败 → 自动提示
  await form.value.validate()
  await userRegisterService(formModel.value)
  ElMessage.success('注册成功')
  isRegister.value = false
}

const userStore = useUserStore()
const router = useRouter()
const login = async () => {
  await form.value.validate()
  const res = await userLoginService(formModel.value)
  userStore.setToken(res.data.data.token)
  ElMessage.success('欢迎登录天下新闻')
  userStore.getUser()
  router.push('/newsNavigation')
}

//聚焦密码框
const passwordInput = ref(null)
const mima = () => {
  passwordInput.value.focus()
}

//记住我
const remember = ref(false)

// 切换的时候，重置表单内容
watch(isRegister, () => {
  formModel.value = {
    userId: '',
    nickname: '',
    email: '',
    code: '',
    password: '',
    repassword: ''
  }
})

//登录管理员界面
const goAdmin = async () => {
  await form.value.validate()
  const res = await userLoginAdminService(formModel.value)
  userStore.setToken(res.data.data.token)
  ElMessage.success(`欢迎管理员登录系统，天下新闻为您服务！`)
  router.push('/admin')
}
</script>

<template>
  <el-row class="login-page">
    <el-col :span="14" class="bg"></el-col>
    <el-col :span="6" :offset="2" class="form">
      <!-- 注册相关表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <div class="centered-container color1">
          <h1>注册</h1>
        </div>
        <el-form-item prop="nickname">
          <el-input
            v-model="formModel.nickname"
            :prefix-icon="User"
            placeholder="注册用户名"
            ref="passwordInput"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="formModel.email"
            :prefix-icon="Message"
            placeholder="请输入绑定邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div class="check">
            <el-input
              v-model="formModel.code"
              :prefix-icon="EditPen"
              placeholder="请输入验证码"
              style="width: 63%"
            ></el-input>
            <el-button
              type="info"
              plain
              style="width: 35%"
              :disabled="isDisabled"
              @click="startCountdown"
            >
              {{ isDisabled ? `（ ${countdown}s ）重新获取` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="register" class="button" type="warning" auto-insert-space>
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录相关表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <div class="centered-container color2">
          <h1>登录</h1>
        </div>
        <el-form-item prop="userId">
          <el-input
            v-model="formModel.userId"
            :prefix-icon="User"
            placeholder="请输入账号"
            @keyup.enter="mima"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            ref="passwordInput"
            @keyup.enter="login"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="remember">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="login" class="button" type="primary" auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item>
          <div class="flex">
            <el-link type="info" :underline="false" @click="isRegister = true">
              注册 →
            </el-link>
            <el-link type="info" :underline="false" style="float: right" @click="goAdmin">
              管理员界面
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background: url('@/assets/login_bg.png') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .centered-container {
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: '华文隶书';
    font-size: 20px;
  }
  .color1 {
    color: #f0791b;
  }
  .color2 {
    color: #379bff;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
.check {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
</style>
